<template>
    <MBX title1="用户管理" title2="用户列表"></MBX>
    <!-- 主体 -->
    <el-card class="mt16">
        <!-- 搜索和添加用户区 -->
        <el-row :gutter="16">
            <!-- 搜索输入框 -->
            <el-col :span="8">
                <el-input clearable @input="getUserFD" @clear="getUserList" v-model="userInfo.query" placeholder="请输入内容"
                    class="input-with-select">

                    <template #append>
                        <el-button @click="getUserList" :icon="Search" />
                    </template>
                </el-input>

            </el-col>
            <!-- 添加按钮区 -->
            <el-col :span="16">
                <el-button type="primary" @click="addUser">添加用户</el-button>

            </el-col>
        </el-row>
        <!-- 用户表格 -->
        <el-table class="mt16" border :data="userList">
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <el-table-column label="状态" prop="">
                <template #default="scope">
                    <div>
                        <el-switch v-model="scope.row.mg_state" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" prop="">
                <template #default="scope">
                    <div>
                        <!-- 编辑 -->
                        <el-button type="primary" :icon="Edit" size="small"></el-button>
                        <!-- 删除 -->
                        <el-button type="danger" :icon="Delete" size="small"></el-button>
                        <!-- 分配角色 -->
                        <el-button @click="openSetRoleDia(scope.row)" type="warning" :icon="Setting"
                            size="small"></el-button>

                    </div>
                </template>

            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination class="mt16" v-model:current-page="userInfo.pagenum" v-model:page-size="userInfo.pagesize"
            :page-sizes="[2, 5, 8]" layout="total, sizes, prev, pager, next, jumper" :total="userTotal"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 打开分配角色对话框 -->
    <el-dialog v-model="isSetDia" title="分配角色">
        <el-form :model="currentUser">
            <el-form-item label="当前用户:">
                <span>{{ currentUser.username }}</span>
            </el-form-item>

            <el-form-item label="当前角色">
                <span>{{ currentUser.role_name }}</span>
            </el-form-item>

            <el-form-item label="新角色id">
                <span>{{ currentUser.roleid }}</span>
            </el-form-item>

            <el-form-item label="分配新角色">
                <el-select v-model="currentUser.roleid" placeholder="请选择新的角色">
                    <el-option v-for="item in rolesArr" :key="item.id" :label="item.roleName" :value="item.id" />

                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isSetDia = false">Cancel</el-button>
                <el-button type="primary">
                    Confirm
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="isAddUser" title="添加新用户" width="50%" :before-close="handleClose">
        <el-form label-width="100px" ref="addUserFormRef" :model="addUserForm" :rules="addUserFormRules">
            <el-form-item label="用户名">
                <el-input v-model="addUserForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>

            <el-form-item label="密码">
                <el-input v-model="addUserForm.password" placeholder="请输入密码"></el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addUserForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>

            <el-form-item label="电话" prop="mobile">
                <el-input v-model="addUserForm.mobile" placeholder="请输入电话"></el-input>
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="isAddUser = false">取消</el-button>
                <el-button type="primary">
                    添加
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { Search, Delete, Edit, Setting } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue'
import { getUserListApi, getRoleListApi } from '@/http/api'
import type { FormInstance, FormRules } from 'element-plus'
import _ from 'lodash'

//是否分配角色
const isSetDia = ref(false)
//是否添加用户
const isAddUser = ref(false)



//用户列表数组
const userList = ref([])
//用户分页查询参数
const userInfo = reactive({
    query: '',
    pagenum: 1,
    pagesize: 5
})

//用户总数
const userTotal = ref(0)

//添加用户表单ref
const addUserFormRef = ref<FormInstance>()

//添加用户信息对象
const addUserForm = reactive({
    username: '',
    password: '',
    email: '',
    mobile: ''
})

//验证邮箱正则
const checkEmail = (rule: any, value: any, callback: any) => {
    //写一个邮箱的正则
    const reg = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;

    if (!reg.test(value)) {
        return callback(new Error('您输入的邮箱格式不对，请检查，例如：xxxx@xxxx.com'))
    }

    callback()

}

//验证手机号正则
const checkMobile = (rule: any, value: any, callback: any) => {
    //写一个手机号的正则
    const reg = /^1[3456789]\d{9}$/;

    if (!reg.test(value)) {
        return callback(new Error('您输入的手机号格式不对，请检查，例如：1xxxxxxx'))
    }

    callback()

}

//配置添加新的表单正则
const addUserFormRules = reactive<FormRules>({
    username: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
        { min: 5, max: 20, message: '用户名长度在5~~~20之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
        { min: 5, max: 20, message: '密码长度在5~~~20之间', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '邮箱不能为空', trigger: 'blur' },
        { validator: checkEmail, trigger: 'blur' }
    ],
    mobile: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { validator: checkMobile, trigger: 'blur' }
    ]
})



onMounted(() => {
    getUserList()
})


const currentUser = reactive({
    id: -1,
    role_name: '',
    username: '',
    roleid: ''

})

//添加用户按钮
const addUser = () => {
    //先显示添加对话框
    isAddUser.value = true
}

//角色列表数组
interface roleItem {
    id: number;
    roleDesc: string;
    roleName: string;
}
const rolesArr = ref<roleItem[]>([])

//打开分配角色对话框
const openSetRoleDia = async (row: any) => {
    console.log('row:', row)
    currentUser.id = row.id
    currentUser.username = row.username
    currentUser.role_name = row.role_name

    //调用角色列表接口
    const res = await getRoleListApi()
    console.log('角色列表:', res)
    rolesArr.value = res.data

    isSetDia.value = true;
}

//搜索防抖
// const getUserFD = _.debounce(() => {
//     getUserList()
// }, 300)

//搜索节流
const getUserFD = _.throttle(() => {
    getUserList()
}, 3000)

//关闭清除用户信息
const handleClose = () => {

}


//每页条数改变时触发
const handleSizeChange = (val: number) => {
    console.log('每页条数:', val)
    userInfo.pagesize = val;
    getUserList()
}
//当前页码改变时触发
const handleCurrentChange = (val: number) => {
    console.log('当前页码:', val)
    userInfo.pagenum = val;
    getUserList()
}

//获取用户列表方法
const getUserList = async () => {
    //调用用户接口
    const res = await getUserListApi(userInfo)
    console.log('用户返回：', res)
    const { total, users } = res.data;
    userList.value = users
    userTotal.value = total;

}
</script>

<style scoped></style>